package edu.whut.mall.common.service.impl;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import edu.whut.mall.common.constant.FileConstant;
import edu.whut.mall.common.service.IFdfsService;
import edu.whut.mall.common.vo.FileVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * @program: d9lab-mall
 * @description: 文件服务实现类
 * @author: Wayne
 * @create: 2020-06-17 17:23
 **/
@Service
@Slf4j
public class FdfsServiceImpl implements IFdfsService {

    private FastFileStorageClient fastFileStorageClient;

    @Autowired
    public void setFastFileStorageClient(FastFileStorageClient fastFileStorageClient) {
        this.fastFileStorageClient = fastFileStorageClient;
    }

    public static String getFileFullPath(String fileStorePath) {
        return FileConstant.fastDfsHost + fileStorePath;
    }

    @Override
    public FileVo upload(MultipartFile file) throws Exception {
        String fileName = file.getOriginalFilename();
        log.info("上传文件：{}", fileName);
        String fileExtName = fileName.substring(fileName.lastIndexOf(".") + 1);
        StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(), fileExtName, null);
        String relativeAddress = storePath.getFullPath();
        return new FileVo(relativeAddress, getFileFullPath(relativeAddress));
    }
}
